import React, { Component } from "react";
import { Text, View, StyleSheet, TouchableOpacity, Image, TextInput, Linking, Platform, FlatList } from 'react-native';
import Constant from '../../utils/Constant'//全局变量
import { getImgUrl } from '../../utils/ComFunction';
import HttpUtils from "../../utils/HttpUtils";
import HttpUrls from "../../utils/HttpUrls";
import Header from "../../components/header";
import { ToastToUser } from "../../utils/CustomToast";
import Loading from "../../utils/Loading";
import DatePickerPart from '../../components/Tool/DatePickerPart'
import { detectionStatus } from '../../utils/Enum'
import { conditionObjWithType } from '../../utils/Conditions'
import StatusBarSelf from "../../components/StatusBarSelf";
import moment from 'moment';
import AsyncImage from "../../components/image/AsyncImage";


let navigation = null;
let pageSize = 20
let pageNo = 1;
let itemNo = 0;

const isIos = Platform.OS == 'ios';

export default class DetectionListPage extends Component {

    constructor(props) {
        super(props);
        this.state = {
            detectionList: [],
            keywordInputText: '',
            isRefresh: false,
            showFoot: 0, // 控制foot， 0：隐藏footer  1：已加载完成,没有更多数据   2 ：显示加载中
            showDatePicker: false,
            showDatePickerType: '',
            orderTime: '',
            reportTime: '',
            inspectorUserId: '', //检测师id
            inspectorUserName: '', //检测师id

            filterShowList: [],
        };
    }

    componentDidMount() {
        this.getDetectionList(true)
    }

    refreshData = () => {
        this.getDetectionList(true);
    }

    _onEndReached() {
        //如果是正在加载中或没有更多数据了，则返回
        if (this.state.showFoot != 0) {
            return null;
        }

        //底部显示正在加载更多数据
        this.setState({ showFoot: 2 });

        this.getDetectionList(false);
    }

    render() {
        navigation = this.props.navigation;
        return (
            <View
                style={styles.container}>

                <StatusBarSelf color='#ffffff'></StatusBarSelf>

                {this.renderNavigationBar()}
                {this.renderFilterBar()}

                {this.state.filterShowList.length > 0 && this.renderFilterShow()}

                {this.renderList()}

                <DatePickerPart type={'YYYY-MM-DD'} defaultDate={this.state[this.state.showDatePickerType]} show={this.state.showDatePicker} changeState={
                    (val) => { // 时间选择组件显示与否
                        this.setState({
                            showDatePicker: val,
                        })
                    }
                } changeDate={(date) => {

                    if (this.state.showDatePickerType == 'orderTime') {
                        let orderTimeFilter = {
                            key: 'orderTime',
                            title: '下单时间' + date,
                            value: date,
                        }
                        this.addFilter(orderTimeFilter)
                    } else if (this.state.showDatePickerType == 'reportTime') {
                        let orderTimeFilter = {
                            key: 'reportTime',
                            title: '报告时间' + date,
                            value: date,
                        }
                        this.addFilter(orderTimeFilter)
                    }

                    this.setState({
                        [this.state.showDatePickerType]: date,
                    }, function () {
                        this.getDetectionList(true)
                    })
                }} />

            </View>
        );
    }

    renderFilterShow() {
        return (
            <View style={styles.filterShowContain}>
                {this.state.filterShowList.map((item, index) => {
                    if (item.key == 'clear') {
                        return (
                            <TouchableOpacity
                                key={index}
                                style={styles.filterShowItem}
                                onPress={() => {
                                    this.clearFilterShow()

                                }}>
                                <Image style={styles.filterShowClearImg} source={require('source/image/comm/btn_clear_history.png')}></Image>
                                <Text style={styles.filterShowText}>清空</Text>

                            </TouchableOpacity>
                        )
                    } else {
                        return (
                            <TouchableOpacity
                                key={index}
                                style={styles.filterShowItem}
                                onPress={() => {
                                    this.removeFilterShow(item, index)

                                }}>
                                <Text style={styles.filterShowText}>{item.title}</Text>
                                <Image style={styles.filterShowCloseImg} source={require('source/image/comm/icon_close.png')}></Image>
                            </TouchableOpacity>
                        )
                    }

                })
                }
            </View>
        )
    }

    clearFilterShow() {

        this.setState({
            orderTime: '',
            reportTime: '',
            inspectorUserId: '',
            keywordInputText: '',
            filterShowList: [],
        }, function () {
            this.refreshData()
        })
    }

    removeFilterShow(item, index) {
        let filterShowList = this.state.filterShowList
        let temp = []
        for (let i = 0; i < filterShowList.length; i++) {
            if (i != index) {
                temp.push(filterShowList[i])
            }
        }

        if (item.key == 'keyword') {
            this.setState({
                keywordInputText: ''
            })
        }

        else if (item.key == 'orderTime') {
            this.setState({
                orderTime: ''
            })
        }
        else if (item.key == 'reportTime') {
            this.setState({
                reportTime: '',

            })
        }
        else if (item.key == 'inspectorUserId') {
            this.setState({
                inspectorUserId: '',
                inspectorUserName: ''
            })
        }


        if (temp.length == 1) {
            temp = []
        }

        this.setState({
            filterShowList: temp
        }, function () {
            this.refreshData()
        })
    }

    renderNavigationBar() {
        return (
            <View
                style={[styles.topContain, { height: isIos ? 44 : 49 }]}>
                <TouchableOpacity
                    style={styles.iconContain}
                    onPress={() => {
                        navigation.goBack();
                    }}>
                    <Image style={styles.iconImg} source={require('source/image/workCenter/home_icon.png')}></Image>
                </TouchableOpacity>

                <View
                    style={styles.searchContain}>
                    <Image style={styles.searchImg} source={require('source/image/comm/icon_sc_search.png')}></Image>
                    <TextInput
                        placeholder="请输入车辆名称或车架号"
                        style={styles.searchInput}
                        clearButtonMode="while-editing"
                        value={this.state.keywordInputText}
                        onChangeText={(text) => { this.setState({ keywordInputText: text }) }}
                        returnKeyType='search'
                        onSubmitEditing={() => { this.search() }}>

                    </TextInput>
                </View>

            </View>
        )
    }

    renderFilterBar() {
        return (
            <View style={styles.filterBar}>
                <TouchableOpacity
                    style={styles.filterItemBox}
                    activeOpacity={0.8}
                    onPress={() => {
                        this.setState({
                            showDatePickerType: 'orderTime',
                            showDatePicker: true
                        })
                    }}
                >
                    <Text style={styles.filterText}>{this.state.orderTime ? this.state.orderTime : '下单时间'}</Text>
                    <Image style={styles.arrowImg} source={require('source/image/comm/down_small_gray.png')} />
                </TouchableOpacity>
                <TouchableOpacity
                    style={[styles.filterItemBox, { justifyContent: 'center' }]}
                    activeOpacity={0.8}
                    onPress={() => {
                        this.setState({
                            showDatePickerType: 'reportTime',
                            showDatePicker: true
                        })
                    }}
                >
                    <Text style={styles.filterText}>{this.state.reportTime ? this.state.reportTime : '报告时间'}</Text>
                    <Image style={styles.arrowImg} source={require('source/image/comm/down_small_gray.png')} />
                </TouchableOpacity>
                <TouchableOpacity
                    style={[styles.filterItemBox, { justifyContent: 'flex-end' }]}
                    activeOpacity={0.8}
                    onPress={() => {
                        navigation.navigate('SellerSelectPage', {
                            isDetection: true,
                            selectedUserId: this.state.inspectorUserId,
                            selectCompletion: (item) => {

                                let obj = {
                                    key: 'inspectorUserId',
                                    title: item.fullname,
                                    value: item.userId
                                }
                                this.addFilter(obj)

                                this.setState({
                                    inspectorUserId: item.userId,
                                    inspectorUserName: item.fullname
                                }, function () {
                                    setTimeout(() => {
                                        this.getDetectionList(true)
                                    }, 500);
                                })
                                navigation.goBack()
                            }
                        })
                    }}
                >
                    <Text style={styles.filterText}>{this.state.inspectorUserName ? this.state.inspectorUserName : '检测师'}</Text>
                    <Image style={styles.arrowImg} source={require('source/image/comm/down_small_gray.png')} />
                </TouchableOpacity>
            </View>
        )
    }

    renderList() {
        return (
            <View style={{ backgroundColor: '#f9f9f9', flex: 1, }}>
                <FlatList
                    data={this.state.detectionList}
                    renderItem={this.renderItemView.bind(this)}
                    extraData={this.state}
                    ListFooterComponent={this.renderFooter.bind(this)}
                    onEndReached={this._onEndReached.bind(this)}
                    onEndReachedThreshold={0.2}
                    onRefresh={this.refreshData}
                    refreshing={this.state.isRefresh}
                    ListEmptyComponent={this.renderEmpty.bind(this)}
                />
            </View>
        )
    }

    renderItemView({ item, index }) {
        return (
            <View key={index} style={styles.itemContain}>
                <View style={styles.sepLine} />
                <TouchableOpacity
                    style={styles.itemBox}
                    activeOpacity={0.8}
                    onPress={() => {
                        navigation.navigate('DetectionDetailPage', {
                            data: item.value,
                            completion: () => {
                                navigation.goBack()
                                this.getDetectionList(true)
                            },
                        })
                    }}
                >
                    <View style={styles.itemTopBox}>
                        {
                            item.value.detectionStatus == detectionStatus.detectionStatusWaitForDetection || item.value.detectionStatus == detectionStatus.detectionStatusDetecting || item.value.detectionStatus == detectionStatus.detectionStatusDetectionCanceled ?
                                <Text style={styles.timeText}>{'下单时间：' + moment(item.value.orderTime).format("YYYY-MM-DD HH:mm")}</Text>
                                :
                                //已完成
                                item.value.detectionStatus == detectionStatus.detectionStatusDetected ?
                                    <Text style={styles.timeText}>{'生成时间：' + moment(item.value.reportTime).format("YYYY-MM-DD HH:mm")}</Text>
                                    :
                                    <Text></Text>
                        }
                        <Text style={[styles.detectionStatusText, { color: item.value.detectionStatus == detectionStatus.detectionStatusDetected ? '#49CC69' : item.value.detectionStatus == detectionStatus.detectionStatusDetectionCanceled ? '#999' : '#FF7B00' }]}>{conditionObjWithType('detectionStatus')[item.value.detectionStatus]}</Text>
                    </View>
                    <View style={styles.carInfoBox}>
                        <AsyncImage style={styles.carImg} source={{ uri: getImgUrl(item.value.mainPic) }} defaultSource={require('source/image/comm/sc_default.png')} />
                        <View style={styles.carInfoBoxRight}>
                            <Text style={styles.carNameText} numberOfLines={1}>{item.value.carName} {item.value.carName}</Text>
                            <Text style={styles.vcodeText}>{'VIN:' + item.value.vcode}</Text>
                            <View style={{ flexDirection: 'row', alignItems: 'center', marginTop: 30, justifyContent: 'flex-start' }}>
                                <Text style={styles.detectionTypeText}>{item.value.detectionTypeName}</Text>
                                <Text style={[styles.detectionTypeText, { marginLeft: 16 }]}>{'检测师：' + (item.value.inspectorName ? item.value.inspectorName : '-')}</Text>
                            </View>
                        </View>
                    </View>
                    {
                        item.value.detectionStatus == detectionStatus.detectionStatusWaitForDetection ?
                            <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'flex-end', marginTop: 10, }}>
                                <TouchableOpacity
                                    style={styles.detectionBtn}
                                    onPress={() => {
                                        let url = 'https://cmg-report.kmruizhi.net/app/appdown.html?orderNo=' + item.value.orderNo + '&inspector=' + item.value.inspectorUserId
                                        console.log('url = ', url);
                                        Linking.openURL(url).catch(err => console.error('An error occurred', err));
                                    }}
                                >
                                    <Text style={styles.detectionText}>{'立即检测'}</Text>
                                </TouchableOpacity>
                            </View>
                            :
                            null
                    }

                </TouchableOpacity>
            </View>
        )
    }

    renderFooter() {
        if (this.state.detectionList.length == 0) {
            return null;
        }
        if (this.state.showFoot === 1) {
            return <View style={{ height: Constant.bottomHeight }} />;
        } else if (this.state.showFoot === 2) {
            return (
                <View style={styles.footer}>
                    <ActivityIndicator size="small" color="#999999" />
                    <Text style={styles.loadMoreTextStyle}>正在加载更多数据...</Text>
                </View>
            );
        } else if (this.state.showFoot === 0) {
            return null;
        }
    }

    renderEmpty() {
        if (!this.state.isRefresh) {
            return (
                <NoData Desc="暂无数据" style={{ marginTop: gREM(200) }} />
            )
        } else {
            return (
                null
            )
        }
    }

    addFilter(filterModel) {
        let filterShowList = this.state.filterShowList
        let clear = {
            key: 'clear',
        }
        if (filterShowList.length == 0) {
            filterShowList.push(filterModel)
            filterShowList.push(clear)

        } else {
            let isExist = false
            for (let i = 0; i < filterShowList.length; i++) {
                if (filterShowList[i].key == filterModel.key) {
                    isExist = true
                    filterShowList[i] = filterModel
                }
            }

            if (isExist) {

            } else {
                filterShowList.splice(filterShowList.length - 2, 0, filterModel);
                // filterShowList.push(filterModel)
            }
        }
        console.log('filterShowList', filterShowList)
        this.setState({
            filterShowList: filterShowList
        })
    }


    search() {

        if (this.state.keywordInputText != '') {
            let keywordObj = {
                title: this.state.keywordInputText,
                key: 'keyword',
                value: this.state.keywordInputText
            }
            this.addFilter(keywordObj)
        }

        this.getDetectionList(true)
    }

    getDetectionList(refresh) {
        if (refresh) {
            pageNo = 1;
            itemNo = 0;
            this.setState({ isRefresh: true })
        } else {
            pageNo++;
        }

        let param = {
            pageNo: pageNo,
            pageSize: pageSize,
            merchantId: Constant.userInfo.merchantId,
        }

        if (this.state.keywordInputText) {
            if (this.state.keywordInputText.length == 17) {
                param.vcode = this.state.keywordInputText
            } else {
                param.keywords = this.state.keywordInputText
            }
        }
        if (this.state.orderTime) {
            param.orderTimeBegin = this.state.orderTime + ' 00:00:00'
            param.orderTimeEnd = this.addDayFromDateString(this.state.orderTime) + ' 00:00:00'
        }
        if (this.state.reportTime) {
            param.reportTimeBegin = this.state.reportTime + ' 00:00:00'
            param.reportTimeEnd = this.addDayFromDateString(this.state.reportTime) + ' 00:00:00'
        }
        if (this.state.inspectorUserId) {
            param.inspectorUserIds = [this.state.inspectorUserId]
        }

        HttpUtils.postRequest(HttpUrls.queryDetectionOrder, param)
            .then((result) => {
                if (refresh) {
                    this.setState({ detectionList: [] })
                }
                let data = result.data
                if (data) {
                    let resultList = data.resultList
                    let dataBlob = [];
                    let i = itemNo;
                    if (resultList && resultList != null && resultList.length > 0) {
                        resultList.map(function (item) {
                            dataBlob.push({
                                key: i,
                                value: item,
                            })
                            i++;
                        });
                        itemNo = i;
                        this.setState({
                            detectionList: this.state.detectionList.concat(dataBlob),
                            isRefresh: false,
                            showFoot: 1,
                        });
                        setTimeout(() => {
                            this.setState({
                                showFoot: dataBlob.length >= pageSize ? 0 : 1,
                            })
                            resultList = null;
                            dataBlob = null;
                        }, 200);
                    } else {
                        this.setState({
                            showFoot: 1,
                            isRefresh: false,
                        });
                    }
                } else {
                    this.setState({
                        showFoot: 1,
                        isRefresh: false,
                    });
                }
            })
            .catch((error) => {

            });
    }

    addDayFromDateString(dateStr) {
        // 1. 将字符串转为 Date 对象
        const date = new Date(dateStr);

        // 2. 检查日期是否有效
        if (isNaN(date.getTime())) {
            throw new Error("Invalid date string");
        }

        // 3. 加一天
        date.setDate(date.getDate() + 1);

        // 4. 重新格式化为 YYYY-MM-DD 字符串
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始
        const day = String(date.getDate()).padStart(2, '0');

        return `${year}-${month}-${day}`;
    }

};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#fff',
        flexDirection: 'column',

    },

    topContain: {
        width: '100%',
        height: 44,
        backgroundColor: '#ffffff',
        flexDirection: 'row',
        alignItems: 'center',

    },

    iconImg: {
        width: 28,
        height: 28
    },
    iconContain: {
        height: '100%',
        justifyContent: 'center',
        alignItems: 'center',
        width: 48
    },
    searchContain: {
        flexDirection: 'row',
        alignItems: 'center',
        flex: 1,
        height: 34,
        backgroundColor: '#f6f6f6',
        borderRadius: 4,
        paddingHorizontal: 15,
        marginRight: 15
    },
    searchInput: {
        flex: 1,
        height: '100%',
        padding: 0,
        marginLeft: 10,
        fontSize: 14,
        color: '#333333',
        height: '100%'
    },

    filterBar: {
        width: '100%',
        height: 46,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        paddingHorizontal: 16,
    },
    filterItemBox: {
        flex: 1,
        height: '100%',
        alignItems: 'center',
        flexDirection: 'row',
    },
    filterText: {
        fontSize: 14,
        color: '#666',
    },
    arrowImg: {
        width: 20,
        height: 20,
    },
    itemContain: {
        width: '100%',
        flexDirection: 'column',
    },
    sepLine: {
        width: '100%',
        height: 10,
    },
    itemBox: {
        paddingBottom: 15,
        width: '100%',
        flex: 1,
        paddingHorizontal: 16,
        flexDirection: 'column',
        backgroundColor: '#fff'
    },
    itemTopBox: {
        width: '100%',
        height: 44,
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        borderBottomColor: '#e4e4e4',
        borderBottomWidth: 0.3,
    },
    timeText: {
        fontSize: 12,
        color: '#333',
    },

    detectionStatusText: {
        fontSize: 14,
        color: '#FF7B00'
    },

    carInfoBox: {
        marginTop: 12,
        width: '100%',
        flexDirection: 'row',
        justifyContent: 'flex-start',
        alignItems: 'center',
    },
    carImg: {
        width: 130,
        height: 90,
        borderRadius: 4,
        backgroundColor: '#f5f5f5'
    },
    carInfoBoxRight: {
        paddingVertical: 10,
        marginLeft: 12,
        flex: 1,
        height: '100%',
        flexDirection: 'column',
        justifyContent: 'flex-start',
    },
    carNameText: {
        fontSize: 14,
        color: '#333333',
        fontWeight: '500',
        marginBottom: 4,
    },
    vcodeText: {
        fontSize: 14,
        color: '#666666'
    },
    detectionTypeText: {
        fontSize: 14,
        color: '#333'
    },
    detectionBtn: {
        justifyContent: 'center',
        alignItems: 'center',
        width: 84,
        height: 32,
        borderRadius: 16,
        backgroundColor: '#FFE000',
    },
    detectionText: {
        fontSize: 14,
        color: '#333'
    },


    footer: {
        flexDirection: 'row',
        height: 40,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#f6f6f6'
    },
    loadMoreTextStyle: {
        fontSize: 14,
        color: '#999999',
        marginStart: 10,
    },

    filterShowContain: {
        flexDirection: 'row',
        flexWrap: 'wrap',
        backgroundColor: '#fff',
        paddingHorizontal: 15
    },
    filterShowItem: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        height: 30,
        backgroundColor: '#f6f6f6',
        borderRadius: 4,
        paddingHorizontal: 10,
        marginRight: 10,
        marginBottom: 5
    },
    filterShowText: {
        fontSize: 12,
        color: '#696969'
    },
    filterShowCloseImg: {
        width: 12,
        height: 12,
        marginLeft: 2
    },
    filterShowClearImg: {
        width: 15,
        height: 15,
        marginRight: 2,
        resizeMode: 'contain'
    },



});